package cn.gov.sdcj.accountancy.rule

/**
 * <p>Description: 领域文件脚步加载器
 * </p>
 *
 * Created by laijie on 2015/3/27.
 */
class ScriptLoader {

    /**
     * 加载指定脚步文件
     * @param fileName 脚步文件路径+名称
     * @return 脚步对象
     * @throws IOException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static Object load(String fileName) throws IOException, IllegalAccessException, InstantiationException {
        File file = new File(fileName);
        return load(file);
    }

    /**
     * 加载指定脚步文件
     *
     * @param file 脚步文件对象
     * @return 脚步对象
     * @throws IOException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static Object load(File file) throws IOException, IllegalAccessException, InstantiationException {
        GroovyClassLoader loader = new GroovyClassLoader();
        Script script = (Script) (loader.parseClass(file).newInstance());
        return script.run();
    }

    /**
     * 加载指定目录下的所有脚步文件
     *
     * @param dirName 目录路径
     * @throws IllegalAccessException
     * @throws IOException
     * @throws InstantiationException
     */
    public static void loadAll(String dirName) throws IllegalAccessException, IOException, InstantiationException {
        File dir = new File(dirName);
        if (!dir.isDirectory()) {
            return;
        }
        File[] files = dir.listFiles();
        if (null != files) {
            for (File dslFile : files) {
                load(dslFile);
            }
        }
    }

    /**
     * 加载指定目录下的所有脚步文件
     *
     * @param dir 目录对象
     * @throws IllegalAccessException
     * @throws IOException
     * @throws InstantiationException
     */
    public static void loadAll(File dir) throws IllegalAccessException, IOException, InstantiationException {
        if (!dir.isDirectory()) {
            return;
        }
        File[] files = dir.listFiles();
        if (null != files) {
            for (File dslFile : files) {
                load(dslFile);
            }
        }
    }
}
